import { isFalse } from '@utils/common';
import { isMobile } from '@utils/is';
import { ErrorModel, SuccessModel } from '@utils/respond/ResModel';
import { MobileUser } from '@modules/mobile/mobileUser/models/mobileUserModel';

// 移动端用户登录
export async function mobileUserLogin({ phone, phoneCode }, ctx) {
  if (!isMobile(phone)) {
    return new ErrorModel({ message: '请正确输入手机号', data: {} });
  }
  if (isFalse(phoneCode)) {
    return new ErrorModel({ message: '验证码错误', data: {} });
  }
  // 验证码正确,手机号正确
  let user;
  user = await MobileUser.findOne({ where:{phone} });
  if (!user) {
    user = await MobileUser.create({ phone });
  }
  return new SuccessModel({
    data: user,
    token: ctx.setJwtSession(
      {
        phone: user.phone,
        userId: user.id,
        userName: user.name,
      },
      60 * 60 * 12
    ),
  });
}

// 刷新用户token，每次打开网页的时候调用
export async function refreshToken(id, ctx) {
  let user = await MobileUser.findOne({ id });
  if (user) {
    return new SuccessModel({
      data: user,
      token: ctx.setJwtSession(
        {
          phone: user.phone,
          userId: user.id,
          userName: user.name,
        },
        60 * 60 * 12 * 7
      ),
    });
  } else {
    return new ErrorModel({ message: '用户不存在', data: null });
  }
}
